﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace MySkiPatrol.Security
{
    public static class Core
    {
        // This constant string is used as a "salt" value for the PasswordDeriveBytes function calls.
        // This size of the IV (in bytes) must = (keysize / 8).  Default keysize is 256, so the IV must be
        // 32 bytes long.  Using a 16 character string here gives us 32 bytes when converted to a byte array.
        private const string passSalt = "Natl_Ski_Patrol!";
        private const string passPhrase = "4bf3y3csxc854x1kw6g3l5m8knuilcpxc49o7te47wx9h1v49314lgyyo6jb8t7knatzocd2scvp7drjsq9iakcv6a00a2vdodm78wgxqzc9l9raf0jikp92xxtdbcspgi0urjav9csb72awjpl9jcsz3j9a33ld6mt38wjvpn98xxvvmwtmqi53p1q7a0s6re5k97on5qkw3k25oen79ymnhpe75blpu2hisalf76g0y8z4zkjvclwsri3kthhu4u213jddt8z3imo8p97krpd95or960lppmv46y1g7523lta5tuuk9w2fhswer37sm9dvqk1r7rdmm9nbemgb61gsjgmd1no3yahbfef9s2chigt85k05nvlktlc9xopk3anbscvz66i4pya3ne8hmif3pwhu25b4cre8shgso0ygchuva8mjf8xkujmvu0w1veryj1a5xfsmkyr71ljuirp3tud8vkyn3xlypwc9xhmzfb0wset8h2i4on4po2ach4imdti49aw15poithggrp60fh91smkv69haseizwoz66gyzzlw7ltlsyh6wjgcmq1vv8dpfygk2q0uzia26qc9cnpca7mfgccf5l3rmvg959j2xn7e9e5wdri7i0f8c04pdkpefjfaa3424mfnz8616f2d2v8lg8w55todxtyqyum9nf3wlr94u2jxibbkbtu16zwax2p59f3btsqmrb0pzsa3aqvmhef40k3ojtyj13uey74plpszt42dotz673nu0zb8p23ydhnvyw53m51slgbvip0ptrbyfzezwvzilumbh6frowk12u9knfq02d4l5pgyi57q6i7ruzeb981x6avkqubg4yg8q05rqh9iotvknipo1frtb7evuv7ntqm71y0ttmksyi8dfax84nfp7nwjlaxv9lpx7njohvveuyusy1fjxyj6bwze2h8iopidtb5rr8r8r0v8s3kkuexb1imbn4mzncq5ghznvorp7beb1qmzwoo9r7bapu4mmrkfaqsa4xo6n73q4a9wim2zogd96ox1k43fqz0bycuyzhmk3k6ek74zolqtdi3gznmj4o04ayy6r4z7us6mhjgc03q586yf8eycu2fek13m8x7kljzkchyg69j0yvw30ixd5mcrdr2ffu32v5jo7d3rfi6ljego50lqzufy776lej0b5g5sb7wmf6xmgr7yad9f9d21pkgz6hcwiuf29ocx4yatxtig08a19k2se32rrwfxt13mb4pm0cba294w10zy6bmxrno5ll67jczvpv4vio1x9sp4z6pqxgrif5vogj0f53rp9866v4gi9ooyxj6fvfa2lhgj0gfzomr61zvqzjvt088qhwrwckjqso4ssm6fpgtnxhxyoggbkh1c8p23pim321ecv2ycdf3jfkt0zs7w475anrj2k3q6uplv3k2mh3y4dhxnw23wbpzuw3p4ivs9pxopzxwfqlf080x5tw5izuu5pqz0uy3mbpfft7oy5o6qazlv6kampaav3j09ywkrhsojlhcl76cbo3vp43uangw1ekc97e093e9hb2ao8peixy7zoa4u2940wn4042dt6389ude2t52y1d3gddlx966ta8lnx9k5blcuqx4av20x75zijonrhgjzwezmsq4jkxng09pf8a2759m48248msnu2dxbxhi4xhc9iih9y7i7ecunsvepmwxs9senbehrrx9oxclpku9e9ggpiaj23si1kk0q4uxkprfg36qg9o5rmiitbo41ufnye73dbvlqxppi0zmck3sfnrf216egpwqa3h1v2c4e3etxt0tb2sgrm8bns1b5g400yeejyq97zec8xh91d3ewfyov5e311yyydtyeladbi9s8w2qasarcq3l0qjdjn860feu4jug3p2e66gz3os9r6l7a8yn1wto92ssi7lrxtonnpeuak9vuzett6kwl6e6we43enhv21bxiykkt3dhmxtaoyybnp5qfir8kafm3etsnhbvl02htwjykuffo58cvl";

        // This constant is used to determine the keysize of the encryption algorithm.
        private const int keysize = 256;

        public static string ReadKeyFile(string keyFile)
        {
            string myReturn = string.Empty;

            myReturn = System.IO.File.ReadAllText(keyFile);

            return myReturn;
        }

        public static bool PasswordCheck(string storedPWD, string providedPWD)
        {
            bool myReturn = false;

            //for now, just do a simpe string compare
            myReturn = (storedPWD == providedPWD);

            return myReturn;
        }

        private static Random _random = new Random(Environment.TickCount);

        public static string RandomString(int length)
        {
            string chars = "0123456789abcdefghijklmnopqrstuvwxyz";
            StringBuilder builder = new StringBuilder(length);

            for (int i = 0; i < length; ++i)
                builder.Append(chars[_random.Next(chars.Length)]);

            return builder.ToString();
        }

        public static string Encrypt(string plainText)
        {
            byte[] initVectorBytes = Encoding.UTF8.GetBytes(passSalt);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
            byte[] keyBytes = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] cipherTextBytes = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            return Convert.ToBase64String(cipherTextBytes);
        }

        public static string Decrypt(string cipherText)
        {
            try
            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(passSalt);
                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
                PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
                byte[] keyBytes = password.GetBytes(keysize / 8);
                RijndaelManaged symmetricKey = new RijndaelManaged();
                symmetricKey.Mode = CipherMode.CBC;
                ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
                byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                memoryStream.Close();
                cryptoStream.Close();
                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }
}
